package com.wispx.gateway.core.filter;

import com.wispx.gateway.core.context.GatewayContext;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class FilterChain {

    private List<Filter> filters = new ArrayList<>();

    public FilterChain add(Filter filter) {
        filters.add(filter);
        return this;
    }

    public FilterChain add(List<Filter> filterList) {
        filters.addAll(filterList);
        return this;
    }

    public int size() {
        return filters.size();
    }

    public void sort() {
        filters.sort(Comparator.comparingInt(Filter::getOrder));
    }

    public void doPreFilter(int idx, GatewayContext context) {
        if (0 <= idx && idx < filters.size()) {
            filters.get(idx).doPreFilter(context);
        }
    }

    public void doPostFilter(int idx, GatewayContext context) {
        if (0 <= idx && idx < filters.size()) {
            filters.get(idx).doPostFilter(context);
        }
    }

}
